package 中等.其他;

/**
 * 求 1+2+...+n ，要求不能使用乘除法、for、while、if、else、switch、case等关键
 * 字及条件判断语句（A?B:C）。
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode.cn/problems/qiu-12n-lcof/
 */
public class 求1到n的和_offer64 {

    public static void main(String[] args) {

        System.out.println(sumNums2(10000));

        System.out.println(Integer.highestOneBit(10000));

        System.out.println(Math.pow(2, 13));

        System.out.println(fastMultiply(10000, 9999));

    }

    /**
     * 短路运算符
     *
     * @param n
     * @return
     */
    public static int sumNums(int n) {
        // n==1时，返回
        boolean flag = n > 0 && (n += sumNums(n - 1)) > 0;
        return n;
    }

    /**
     * 快速乘+等差序列求和
     */
    public static int sumNums2(int n) {
        int multiplyPart = 0;
        int A = n, B = n - 1;
        boolean flag;
        // 将循环展开，不判断乘数 > 0 ,因为 0 & 1 == 0 不影响结果
        flag = (A & 1) == 1 && (multiplyPart += B) > 0;
        A >>= 1;
        B <<= 1;
        flag = (A & 1) == 1 && (multiplyPart += B) > 0;
        A >>= 1;
        B <<= 1;
        flag = (A & 1) == 1 && (multiplyPart += B) > 0;
        A >>= 1;
        B <<= 1;
        flag = (A & 1) == 1 && (multiplyPart += B) > 0;
        A >>= 1;
        B <<= 1;
        flag = (A & 1) == 1 && (multiplyPart += B) > 0;
        A >>= 1;
        B <<= 1;
        flag = (A & 1) == 1 && (multiplyPart += B) > 0;
        A >>= 1;
        B <<= 1;
        flag = (A & 1) == 1 && (multiplyPart += B) > 0;
        A >>= 1;
        B <<= 1;
        flag = (A & 1) == 1 && (multiplyPart += B) > 0;
        A >>= 1;
        B <<= 1;
        flag = (A & 1) == 1 && (multiplyPart += B) > 0;
        A >>= 1;
        B <<= 1;
        flag = (A & 1) == 1 && (multiplyPart += B) > 0;
        A >>= 1;
        B <<= 1;
        flag = (A & 1) == 1 && (multiplyPart += B) > 0;
        A >>= 1;
        B <<= 1;
        flag = (A & 1) == 1 && (multiplyPart += B) > 0;
        A >>= 1;
        B <<= 1;
        flag = (A & 1) == 1 && (multiplyPart += B) > 0;
        A >>= 1;
        B <<= 1;
        flag = (A & 1) == 1 && (multiplyPart += B) > 0;
        A >>= 1;
        B <<= 1;
        return n + (multiplyPart >> 1);
    }

    // 被乘数除以2, 乘数乘以2, 如果被乘数除以2以后有余数(余数为1), 则将乘数累加到结果中
    public static int fastMultiply(int a, int b) {
        int ans = 0;
        while (a > 0) {
            if ((a & 1) == 1) ans += b;
            a >>= 1;
            b <<= 1;
        }
        return ans;
    }

}
